package problem2;

//2.两数相加
//https://leetcode.cn/problems/add-two-numbers/

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newHead = new ListNode();
        int t = 0;
        ListNode cur1 = l1, cur2 = l2, cur = newHead;
        while(cur1 != null || cur2 != null) {
            int a = cur1 == null ? 0 : cur1.val;
            int b = cur2 == null ? 0 : cur2.val;
            int s = (a + b + t) % 10;
            t = (a + b + t) / 10;
            cur.next = new ListNode(s);
            if(cur1 != null) cur1 = cur1.next;
            if(cur2 != null) cur2 = cur2.next;
            cur = cur.next;
        }
        if(t > 0) {
            cur.next = new ListNode(t);
        }
        return newHead.next;
    }
}